package com.ghost.alibabaghost.web.controller.sys;

import com.ghost.alibabaghost.api.model.sys.GhostDeptModel;
import com.ghost.alibabaghost.api.service.sys.GhostDeptService;
import com.ghost.alibabaghost.result.SingleResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yaolisheng
 * @version 1.0
 * @date 2022/1/24 05:31
 */

@RestController
@RequestMapping("dept")
public class GhostDeptController {

    private static final Logger logger = LoggerFactory.getLogger(GhostDeptController.class);
    /**
     * 部门菜单首级编码
     */
    private static final String DEPT_PARENT_CODE = "parent";

    private GhostDeptService ghostDeptService;
    @Autowired
    public void setGhostDeptService(GhostDeptService ghostDeptService) {
        this.ghostDeptService = ghostDeptService;
    }

    @RequestMapping("queryDeptTree")
    public SingleResult<List<GhostDeptModel>> queryDeptTree() {

        try {
            List<GhostDeptModel> ghostDeptModels = ghostDeptService.queryAll();
            List<GhostDeptModel> ghostDeptModelList = checkDeptTree(ghostDeptModels, DEPT_PARENT_CODE);
            return SingleResult.buildSuccess(ghostDeptModelList);
        } catch (Exception e) {
            logger.error("出错啦--->", e);
            return SingleResult.buildFailure();
        }
    }

    private List<GhostDeptModel> checkDeptTree(List<GhostDeptModel> ghostDeptModels, String parentCode) {
        List<GhostDeptModel> collect = ghostDeptModels.stream().filter(model -> {
            if (parentCode.equals(model.getParentCode())) {
                String flagCode = model.getDeptCode();
                List<GhostDeptModel> ghostDeptModelList = this.checkDeptTree(ghostDeptModels, flagCode);
                model.setSubdepts(ghostDeptModelList);
                return true;
            }
            return false;
        }).collect(Collectors.toList());
        return collect;
    }

}
